<?php


namespace app\api\controller;

use support\Exception\ApiException;

/**
 * api  统一入口
 */
class IndexController
{
    public function index()
    {

        $all = request()->rawBody();
        $all = json_decode($all, true);
        if (!$all) throw  new ApiException(trans('error'));
        //判断插件是否存在
        if (empty($all['plugin'])) throw  new ApiException(trans('plugin not exist', ['%name%' => '']));
        $plugin_path = base_path('plugin' . DIRECTORY_SEPARATOR . $all['plugin']);
        if (!is_dir($plugin_path)) throw  new ApiException(trans('plugin not exist', ['%name%' => $all['plugin']]));
        if (empty($all['module'])) throw  new ApiException(trans('plugin module not exist', ['%name%' => '']));
        //判断控制器是否存在
        $model = ucfirst(trim($all['module']));
        $plugin_api_path = base_path('plugin' . DIRECTORY_SEPARATOR . $all['plugin'] . DIRECTORY_SEPARATOR .
            'app' . DIRECTORY_SEPARATOR . 'api' . DIRECTORY_SEPARATOR . 'controller' . DIRECTORY_SEPARATOR . $model . '.php');
        if (!is_file($plugin_api_path)) throw  new ApiException(trans('plugin module not exist', ['%name%' => $all['module']]));
        $className = $model;
        $class_path = "\\plugin\\{$all['plugin']}\\app\\api\\controller\\" . $className;
        if (!class_exists($class_path)) throw  new ApiException(trans('plugin module not exist', ['%name%' => $all['module']]));
        if (empty($all['action'])) throw  new ApiException(trans('plugin action not exist', ['%name%' => '']));
        $class = new $class_path();
        if (!method_exists($class, $all['action'])) throw  new ApiException(trans('plugin action not exist', ['%name%' => $all['module'] . ' ' . $all['action']]));
        // 获取控制器鉴权信息
        $reflectionClass = new \ReflectionClass($class_path);
        $properties = $reflectionClass->getDefaultProperties();
        $noNeedLogin = $properties['noNeedLogin'] ?? [];
        // 不需要登录
        if (!in_array($all['action'], $noNeedLogin)) {
            $token = request()->header('token') ?? '';
            if (!$token) {
                return error(403, '请登录');
            }
            //检查用户是否存在
        }
        request()->setApiData($all['data'] ?? []);
        $res = call_user_func([$class, $all['action']]);
        return success($res);
    }

}
